package com.zsw.upload;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.stream.ChunkedWriteHandler;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicLong;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Client {
	
	static final Logger LOG = LoggerFactory.getLogger(Client.class);
	static final boolean SSL = System.getProperty("ssl") != null;
    static final String HOST = System.getProperty("host", "localhost");
    static final int PORT = Integer.parseInt(System.getProperty("port", SSL ? "8992" : "9527"));
    static final int SIZE = Integer.parseInt(System.getProperty("size", "256"));
    
    private ClientHandler handler ;
    
	public void nettyClient(EventLoopGroup group) throws InterruptedException, IOException {
        Bootstrap b = new Bootstrap();
        handler = new ClientHandler();
        b.group(group)
         .channel(NioSocketChannel.class)
         .option(ChannelOption.TCP_NODELAY, true)
         .handler(new ChannelInitializer<SocketChannel>() {
             @Override
             public void initChannel(SocketChannel ch) throws Exception {
                 ch.pipeline().addLast(new ChunkedWriteHandler(),handler);
             }
         });
        Channel f = b.connect(HOST, PORT).sync().channel();
        //等待关闭
        f.closeFuture().sync();
	}
	
    public void excute() throws IOException {
    	EventLoopGroup group = new NioEventLoopGroup();
		try {
			nettyClient(group);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			group.shutdownGracefully();
		}
	}
    
    public static void main(String[] args) throws IOException {
    	AtomicLong i = new AtomicLong(0);
    	while(i.getAndAdd(1) < 5){
    		new Thread(() -> {
    			try {
					new Client().excute();
				} catch (Exception e) {
					e.printStackTrace();
				}
    		}).start();
    	}
    }
}
